<template>
  <el-card class="table-card" shadow="never">
    <template #header>
      <div class="card-header">
        <div class="header-left">
          <span>供应商列表</span>
          <el-tag type="info">{{ pagination.total }} 条记录</el-tag>
        </div>
        <div class="header-right">
          <el-button 
            :icon="Refresh" 
            @click="handleRefresh"
            :loading="loading"
          >
            刷新
          </el-button>
        </div>
      </div>
    </template>
    
    <el-table
      :data="tableData"
      v-loading="loading"
      row-key="id"
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange"
    >
      <el-table-column
        type="selection"
        width="50"
        fixed="left"
      />
      
      <el-table-column
        prop="name"
        label="供应商名称"
        min-width="240"
        sortable
        fixed="left"
      />
      
      <el-table-column
        prop="contactPerson"
        label="联系人"
        width="120"
        :formatter="contactFormatter"
      />
      
      <el-table-column
        prop="phone"
        label="联系电话"
        width="140"
        :formatter="phoneFormatter"
      />
      
      <!-- <el-table-column
        prop="email"
        label="邮箱"
        width="180"
        :formatter="emailFormatter"
      /> -->
      
      <el-table-column
        prop="address"
        label="地址"
        min-width="200"
        :formatter="addressFormatter"
      />
      
      <el-table-column
        prop="status"
        label="状态"
        width="100"
        sortable
      >
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column
        prop="rating"
        label="评分"
        width="120"
      >
        <template #default="{ row }">
          <el-rate
            :model-value="Number(row.rating)"
            disabled
            show-score
            text-color="#ff9900"
            score-template="{value}分"
          />
        </template>
      </el-table-column>
      
      <el-table-column
        prop="createdAt"
        label="创建时间"
        width="120"
        sortable
      >
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      
      <el-table-column
        label="操作"
        width="210"
        fixed="right"
      >
        <template #default="{ row }">
          <div class="table-actions">
            <el-button 
              size="small" 
              @click.stop="viewDetail(row)"
              class="action-btn detail-btn"
            >
              详情
            </el-button>
            <el-button 
              size="small" 
              @click.stop="editSupplier(row)"
              class="action-btn edit-btn"
            >
              编辑
            </el-button>
            <el-dropdown @command="handleMoreAction">
              <el-button size="small" class="el-dropdown-link more-btn">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{action: 'transactions', row: row}">
                    <el-icon><Coin /></el-icon>交易记录
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'activate', row: row}" v-if="row.status !== 'active'">
                    <el-icon><Checked /></el-icon>激活供应商
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'deactivate', row: row}" v-if="row.status === 'active'">
                    <el-icon><Close /></el-icon>停用供应商
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'delete', row: row}" divided>
                    <el-icon><Delete /></el-icon>删除供应商
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="paginationConfig.currentPage"
        v-model:page-size="paginationConfig.pageSize"
        :total="paginationConfig.total"
        :page-sizes="paginationConfig.pageSizes"
        :layout="paginationConfig.layout"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { 
  Refresh, Checked, Close, Delete, ArrowDown, Coin
} from '@element-plus/icons-vue'

interface Supplier {
  id: number
  name: string
  contactPerson: string | null
  phone: string
  email: string
  address: string
  status: string
  rating: string | number
  cooperationDate?: string
  createdAt: string
  updatedAt: string
  // 后端可能返回的下划线命名字段
  contact_person?: string | null
  created_at?: string
  updated_at?: string
}

interface Pagination {
  page: number
  limit: number
  total: number
}

const props = defineProps<{
  suppliers: Supplier[]
  loading: boolean
  pagination: Pagination
  selectedSuppliers: Supplier[]
}>()

// 添加调试日志
console.log('SupplierTable组件接收到的props:', props);

const emit = defineEmits<{
  (e: 'selection-change', selection: Supplier[]): void
  (e: 'row-click', row: Supplier): void
  (e: 'sort-change', sort: { column: any, prop: string, order: string }): void
  (e: 'sort', field: string): void
  (e: 'view-detail', supplier: Supplier): void
  (e: 'edit', supplier: Supplier): void
  (e: 'more-action', command: { action: string, row: Supplier }): void
  (e: 'size-change', size: number): void
  (e: 'current-change', page: number): void
  (e: 'refresh'): void
}>()

// 计算属性
const tableData = computed(() => {
  // 确保数据是数组
  const rawData = Array.isArray(props.suppliers) ? props.suppliers : []
  
  console.log('SimpleSupplierTable接收到的原始数据:', rawData);
  console.log('SimpleSupplierTable接收到的原始数据长度:', rawData.length);
  
  // 如果没有数据，直接返回空数组
  if (rawData.length === 0) {
    console.log('SimpleSupplierTable没有数据返回空数组');
    return []
  }
  
  // 处理字段映射，确保使用正确的字段名
  const processedData = rawData.map((supplier: Supplier, index: number) => {
    console.log(`处理第${index}个供应商数据:`, supplier);
    
    // 处理评分字段，确保是数字类型
    let rating = 0
    if (typeof supplier.rating === 'string') {
      rating = parseFloat(supplier.rating) || 0
    } else if (typeof supplier.rating === 'number') {
      rating = supplier.rating
    }
    
    // 处理联系人字段，兼容不同命名方式
    const contactPerson = supplier.contactPerson !== undefined && supplier.contactPerson !== null ? 
      supplier.contactPerson : 
      (supplier.contact_person !== undefined && supplier.contact_person !== null ? supplier.contact_person : '')
    
    const processedSupplier = {
      ...supplier,
      // 确保使用驼峰命名字段
      contactPerson: contactPerson,
      createdAt: supplier.createdAt || supplier.created_at || '',
      updatedAt: supplier.updatedAt || supplier.updated_at || '',
      // 确保评分是数字类型
      rating: rating,
      // 确保状态字段存在
      status: supplier.status || 'pending'
    }
    
    console.log(`处理后的第${index}个供应商数据:`, processedSupplier);
    return processedSupplier
  })
  
  console.log('SimpleSupplierTable最终表格数据:', processedData);
  console.log('SimpleSupplierTable最终表格数据长度:', processedData.length);
  return processedData
})

const paginationConfig = computed(() => ({
  currentPage: props.pagination.page,
  pageSize: props.pagination.limit,
  total: props.pagination.total,
  pageSizes: [10, 20, 50, 100],
  layout: 'total, sizes, prev, pager, next, jumper'
}))

// 格式化函数
const contactFormatter = (row: Supplier, column: any, cellValue: any) => {
  const value = row.contactPerson || row.contact_person || cellValue || ''
  return value || '-'
}

const phoneFormatter = (row: Supplier, column: any, cellValue: any) => {
  const value = row.phone || cellValue || ''
  return value || '-'
}

const emailFormatter = (row: Supplier, column: any, cellValue: any) => {
  const value = row.email || cellValue || ''
  return value || '-'
}

const addressFormatter = (row: Supplier, column: any, cellValue: any) => {
  const value = row.address || cellValue || ''
  return value || '-'
}

const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  try {
    const date = new Date(dateString)
    if (isNaN(date.getTime())) return dateString
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    })
  } catch (error) {
    return dateString
  }
}

const getStatusType = (status: string) => {
  switch (status) {
    case 'active': return 'success'
    case 'pending': return 'warning'
    case 'suspended': return 'warning'
    case 'terminated': return 'danger'
    default: return 'info'
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'active': return '合作中'
    case 'pending': return '待审核'
    case 'suspended': return '已暂停'
    case 'terminated': return '已终止'
    default: return '未知状态'
  }
}

// 事件处理函数
const handleSelectionChange = (selection: Supplier[]) => {
  emit('selection-change', selection)
}

const handleSortChange = (sort: { column: any, prop: string, order: string }) => {
  emit('sort-change', sort)
}

const handleSort = (field: string) => {
  emit('sort', field)
}

const viewDetail = (supplier: Supplier) => {
  emit('view-detail', supplier)
}

const editSupplier = (supplier: Supplier) => {
  emit('edit', supplier)
}

const handleMoreAction = (command: { action: string, row: Supplier }) => {
  emit('more-action', command)
}

const handleSizeChange = (size: number) => {
  emit('size-change', size)
}

const handleCurrentChange = (page: number) => {
  emit('current-change', page)
}

const handleRefresh = () => {
  emit('refresh')
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-actions {
  display: flex;
  gap: 12px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 按钮动画效果 */
.action-btn,
.more-btn {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.action-btn:hover,
.more-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.action-btn:active,
.more-btn:active {
  transform: translateY(0);
}

.action-btn::after,
.more-btn::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  transform: translate(-50%, -50%);
  transition: width 0.6s, height 0.6s;
}

.action-btn:active::after,
.more-btn:active::after {
  width: 300px;
  height: 300px;
}

/* 详情按钮样式 */
.detail-btn {
  background-color: #409eff;
  border-color: #409eff;
  color: white;
}

.detail-btn:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 编辑按钮样式 */
.edit-btn {
  background-color: #e6a23c;
  border-color: #e6a23c;
  color: white;
}

.edit-btn:hover {
  background-color: #ebb563;
  border-color: #ebb563;
}

/* 下拉按钮样式 */
.more-btn {
  background-color: #909399;
  border-color: #909399;
  color: white;
}

.more-btn:hover {
  background-color: #a6a9ad;
  border-color: #a6a9ad;
}

/* 表格行悬停效果 */
.supplier-row:hover {
  background-color: #f5f7fa !important;
  transform: scale(1.005);
  transition: all 0.3s ease;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .header-right {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    justify-content: center;
  }
}
</style>